package com.xjscrm.server.service.wwgroup.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.MicaConversationMsg;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.entity.WwGroup;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.customer.WwCustomerTagsService;
import com.xjscrm.server.service.wwgroup.WwGroupService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 企业微信群实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class WwGroupServiceImpl implements WwGroupService {

    @Autowired
    private WwGroupMapper wwGroupMapper;
    @Autowired
    private TaskTagAutoMapper taskTagAutoMapper;
    @Autowired
    private TaskTagAutoDeviceMapper taskTagAutoDeviceMapper;
    @Autowired
    private WwTagsMapper wwTagsMapper;
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private WwCustomerTagsService wwCustomerTagsService;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private RatelimitService ratelimitService;

    /**
     * 同步企业微信群
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void wwGroupPush(MicaTransDto micaTransDto) {

        //限流判断(同一个机器人60秒之内只能操作一次)
//        String rateLimitKey = "wwGroupPush-taskId=" + micaTransDto.getDeviceId();
//        boolean inRateLimit = ratelimitService.inRateLimit(rateLimitKey, 1, 60);
//        if (!inRateLimit) {
//            return;
//        }

        log.info("--监控系统日志--进入方法--");

        if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
            log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
            return;
        }

        //查询该机器人
        WwDevice wwDevice  = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
        if(wwDevice == null){
            log.info("未找到该机器人，device={}, merId={}", micaTransDto.getDeviceId(), micaTransDto.getMerId());
            return;
        }

        //更新时间
        int now = DateUtil.getTime();

        //更新最后更新同步群时间
        wwDevice.setLastSyncSuctomerGroupTime(now);
        wwDevice.setUpdateTime(now);
        wwDeviceMapper.update(wwDevice);

        Device device = DeviceTools.transDevice(wwDevice);
        if (device == null) {
            log.info("未找到该机器人，device={}, merId={}", micaTransDto.getDeviceId(), micaTransDto.getMerId());
            return;
        }

        MicaConversationMsg micaConversationMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaConversationMsg.class);
        if (micaConversationMsg != null) {
            List<MicaConversationMsg.ConversationItemMsg> groups = micaConversationMsg.getGroups();
            if (groups != null && groups.size() > 0) {
                for (MicaConversationMsg.ConversationItemMsg group : groups) {
                    //判断存不存在，不存在则添加
                    WwGroup wwGroup = wwGroupMapper.queryByDeviceUniqueIdAndGroupWxid(device.getDeviceUniqueId(), group.getGroupId());

                    if (wwGroup == null) {
                        wwGroup = new WwGroup();
                        wwGroup.setId(IdWorker.getId());
                        wwGroup.setMerId(device.getMerId());
                        wwGroup.setDeviceId(device.getDeviceId());
                        wwGroup.setDeviceUniqueId(device.getDeviceUniqueId());
                        wwGroup.setGroupWxid(group.getGroupId());
                        wwGroup.setGroupName(group.getNickName());
                        wwGroup.setHeadImageUrl(group.getHeadImgUrl());
                        wwGroup.setCreateWxid(group.getCreateWxId());
                        wwGroup.setGroupType(group.getGroupType());
                        wwGroup.setMemberTotal(group.getMemberTotal());
                        wwGroup.setGroupCreateTime(group.getCreateTime());
                        wwGroup.setGroupUpdateTime(group.getUpdateTime());
                        wwGroup.setVersion(0L);
                        wwGroup.setRemark(null);
                        wwGroup.setPushTime(now);
                        wwGroup.setAdminWxIds(JSONObject.toJSONString(group.getAdminWxIds()));
                        wwGroup.setUpdateGroupName(0); //默认否
                        wwGroup.setCreateTime(now);
                        wwGroup.setUpdateTime(now);
                        wwGroupMapper.insert(wwGroup);
                        log.info("--监控系统日志--查新新群--");

                    } else {
//                        wwGroup.setGroupName(group.getNickName());
//                        wwGroup.setHeadImageUrl(group.getHeadImgUrl());
//                        wwGroup.setGroupType(group.getGroupType());
//                        wwGroup.setMemberTotal(group.getMemberTotal());
//                        wwGroup.setGroupCreateTime(group.getCreateTime());
//                        wwGroup.setGroupUpdateTime(group.getUpdateTime());
//                        wwGroup.setCreateWxid(group.getCreateWxId());
//                        wwGroup.setAdminWxIds(JSONObject.toJSONString(group.getAdminWxIds()));
//                        wwGroup.setPushTime(now);
//                        wwGroup.setUpdateTime(now);
//                        wwGroupMapper.updateById(wwGroup);
                    }
                }
            }
        }

        log.info("--监控系统日志--结束方法--");
    }

    /**
     * 变更企业微信群(退群、进群满足条件触发自动打标签功能)
     *
     * @param micaTransDto
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForEvent")
    @TraceGenerate //注入消息id标签
    public void wwGroupChange(MicaTransDto micaTransDto) {

        if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
            log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
            return;
        }

        //查询该机器人
        WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
        if (wwDevice == null) {
            return;
        }
        Device device = DeviceTools.transDevice(wwDevice);
        if (device == null) {
            return;
        }

        //更新时间
        int now = DateUtil.getTime();

    }


}
